import {View, Input, Image} from "@tarojs/components";
import {useRef, useState} from "react";
import Taro from "@tarojs/taro";
import styles from "./login.module.scss"
import {request} from "../../utils/request";
import {apis} from "../../constants/apis";
import EventBus from "../../envent_bus/event_bus";
import {LoginBackMe} from "../../envent_bus/events";
import globalData from "../../global_data";

const countDownTotalSeconds = 60;
const login = () => {
  const [profile, setProfile] = useState<any>();
  const [name, setName] = useState<any>();
  const [phone, setPhone] = useState<any>('');
  const [code, setCode] = useState<any>(); //验证码
  const [isGotUserInfo, setIsGotUserInfo] = useState(false);
  const [codeSendCountDown, setCodeSendCountDown] = useState(countDownTotalSeconds);
  const countDownRef = useRef(countDownTotalSeconds); //倒计时剩余
  const [isCountDown, setIsCountDown] = useState(false); //是否进入倒计时

  const getUserInfo = () => {
    Taro.getUserProfile({
      desc: "获取用户信息",
      success: (res) => {
        setProfile(res.userInfo.avatarUrl);
        setName(res.userInfo.nickName);
        setIsGotUserInfo(true);
      },
      fail: () => {
        Taro.showToast({
          icon: "error",
          title: "请授权用户信息",
        })
      }
    })
  };

  const toLoginRegister = () => {
    if (submitRul()) {
      request({
        url: apis.USER_LOGIN,
        data: {
          phone: phone,
          code: code,
          name: name,
          profile: profile,
        },
        pureData: false,
      }).then(res => {
        if (res.code === 200) {
          globalData.userInfo = res.data;
          globalData.accessToken = res.token;
          EventBus.fire(LoginBackMe.eventName, new LoginBackMe());
          Taro.navigateBack();
        }
      })
    }
  }

  const getCodeToServer = () => {
    if (phone.length <= 0 || phone.length !== 11) {
      Taro.showToast({
        icon: "error",
        title: "手机号错误",
      })
      return;
    }
    const randomCode = Math.floor(Math.random() * (100000 - 10000)) + 10000;
    setIsCountDown(true);
    sendSmsCountDown();
    request({
      url: apis.SEND_CODE,
      method: "GET",
      data: {
        phone: phone,
        code: randomCode
      },
      pureData: false,
    }).then(res => {
      if (res.code === 200) {
        Taro.showToast({
          icon: "success",
          title: res.data,
        })
      }
    })
  }

  const sendSmsCountDown = () => {
    if (countDownRef.current > 0) {
      countDownRef.current = countDownRef.current - 1;
      setCodeSendCountDown(countDownRef.current)
      setTimeout(() => {
        sendSmsCountDown();
      }, 1000);
    } else {
      countDownRef.current = countDownTotalSeconds;
      setCodeSendCountDown(countDownTotalSeconds);
      setIsCountDown(false);
    }
  }

  const uploadImage = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        setProfile(tempFilePaths)
      }
    })
  }


  const inputPhone = (e) => {
    setPhone(e.detail.value);
  }

  const inputCode = (e) => {
    setCode(e.detail.value);
  }

  const submitRul = () => {
    if (!isGotUserInfo) {
      Taro.showToast({
        icon: "error",
        title: "请授权用户信息",
      })
      return false;
    }

    if (phone.length < 11) {
      Taro.showToast({
        title: "手机号格式错误",
        icon: "error",
      });
      return false;
    }
    return true;
  }

  return (
    <View className="container">
      <View className={styles.form}>
        <Image onClick={uploadImage} className={styles.user_avatar} src={profile} mode="aspectFill"/>

        <Input onInput={(e) => {
          inputPhone(e)
        }} placeholder={"请输入手机号"}/>
        <View style={{width: "100%"}} className="divide-1-dark"/>
        <View className={styles.user_code}>
          <View>
            <Input onInput={(e) => {
              inputCode(e)
            }} placeholder={"请输入验证码"}/>
            <View style={{width: "90%"}} className="divide-1-dark"/>
          </View>

          <View style={{display: isCountDown ? 'none' : 'flex'}} onClick={getCodeToServer}
                className={styles.btn_code}>获取验证码</View>
          <View style={{backgroundColor: "#888888", display: isCountDown ? 'flex' : 'none', width: "200rpx"}}
                className={styles.btn_code}>{codeSendCountDown}s可重发</View>
        </View>

        <View style={{display: isGotUserInfo ? 'none' : 'flex'}} onClick={getUserInfo}
              className={styles.user_btn}>授权用户信息</View>
        <View style={{display: isGotUserInfo ? 'flex' : 'none', backgroundColor: 'grey'}}
              className={styles.user_btn}>授权用户信息</View>
        <View onClick={toLoginRegister} className={`${styles.btn_register} item-click text_medium`}>登录/注册</View>
      </View>

    </View>
  )
};
export default login;
